package mqtt.simple.demo;

import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;

public class SimpleMqttClient {

    public static void main(String[] args) {
        String broker = "tcp://localhost:1889";
        String clientId = "168484884";
        MemoryPersistence persistence = new MemoryPersistence();

        try {
            // 创建 MQTT 客户端
            MqttClient client = new MqttClient(broker, clientId, persistence);

            // 设置回调函数
            client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    System.out.println("Connection lost: " + cause.getMessage());
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) throws Exception {
                    System.out.println("Message arrived: " + new String(message.getPayload()));
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    System.out.println("Delivery complete.");
                }
            });

            // 连接 MQTT 代理服务器
            client.connect();

            // 订阅主题
            String topic = "test/topic";
            int qos = 0;
            client.subscribe(topic, qos);

            // 发布消息
            String message = "Hello, world!";
            client.publish(topic, message.getBytes(), qos, false);

            // 断开连接
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

}
